package com.lsh.oms.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/9/21
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Slf4j
public class BaseGoodUtils {

//    public static String GETINFOS = "/goods/sku/getinfos";

    public static String SAAS_GETINFOS = "/v1/Market/Item/getListBySkuIds";;

    /**
     * @param shopServiceUrl
     * @param entity
     * @param logSign
     * @param headers
     * @return
     */
    public static Map<String, Object> doReq(String shopServiceUrl, HttpEntity entity, Header[] headers, String logSign) {
        String res;
        Map<String, Object> obj;
        try {
            long start = System.currentTimeMillis();
            res = HttpUtils.post(shopServiceUrl, entity, false, headers).getData();
            log.info(logSign + "【商品服务耗时是】: {} ms", (System.currentTimeMillis() - start));
            log.info(logSign + "【商品服务返回结果是】: {}", res);
            JSONObject content = JSON.parseObject(res).getJSONObject("content");
            if (content == null) {
                return Collections.emptyMap();
            }
            obj = JsonUtils.json2Obj(res, HashMap.class);
        } catch (Throwable e) {
            log.info(logSign + "【商品服务返回结果转json失败】");
            return Collections.emptyMap();
        }
        obj.put("res", res);
        return obj;
    }

    /**
     * @param shopServiceUrl
     * @param entity
     * @param logSign
     * @param headers
     * @return
     */
    public static JSONObject doReqSaas(String shopServiceUrl, HttpEntity entity, Header[] headers, String logSign) {

        JSONObject content = null;
        try {
            long start = System.currentTimeMillis();
            String res = HttpUtils.post(shopServiceUrl, entity, false, headers).getData();
            log.info(logSign + "【商品服务耗时是】: {} ms", (System.currentTimeMillis() - start));
            log.info(logSign + "【商品服务返回结果是】: {}", res);
            content = JSON.parseObject(res);
            if (content == null ) {
                log.error("商品信息不存在！shopServiceUrl=" + shopServiceUrl);
                return null;
            }
        } catch (Throwable e) {
            log.info(logSign + "【商品服务返回结果转json失败】");
            return null;
        }
        return content;
    }




    public static Header[] buildHeaders(Long venderId) {
        Header[] headers = {new BasicHeader("api-version", "1.1"),
                new BasicHeader("platform", "oms"),
                new BasicHeader("venderId", venderId + ""),
                new BasicHeader("sign", "md5")};
        return headers;
    }
}
